// src/libs/dynamic-modules-loader.ts
import { DynamicModule } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

interface LoadResult {
  success: number;
  fail: number;
}

export class DynamicModuleLoader {
  static async loadModulesFromDirectory(folder: string): Promise<DynamicModule[]> {
    const modules: DynamicModule[] = [];
    const loadResult: LoadResult = { success: 0, fail: 0 };

    async function findFiles(dir: string) {
      const files = fs.readdirSync(dir);
      for (const file of files) {
        const fullPath = path.join(dir, file);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
          await findFiles(fullPath);
        } else if (file.endsWith('.module.js')) {  // 只加载模块文件
          try {
            const module = await import(fullPath);
            // 确保模块名称生成为 PascalCase
            const moduleName = file
              .replace('.module.js', '')
              .replace(/(^\w|-\w)/g, match => match.replace('-', '').toUpperCase()) + 'Module';

            if (module && module[moduleName]) {
              modules.push(module[moduleName]);
              loadResult.success++;
            } else {
              console.error(`未找到模块导出名称 ${moduleName} in ${fullPath}`);
              loadResult.fail++;
            }
          } catch (error) {
            console.error(`加载模块失败: ${fullPath}`, error);
            loadResult.fail++;
          }
        }
      }
    }

    await findFiles(folder);
    console.log(`总模块数: ${modules.length}, 成功加载: ${loadResult.success}, 加载失败: ${loadResult.fail}`);
    return modules;
  }
}
